package czk.concrent.threadpool.newCachedThreadPool.practice;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * 阻塞队列的练习
 *
 * @Author:ChenZhangKun
 * @Date: 2021/6/9 10:55
 */
public class SynchronousQueuePractice {
    public static void main(String[] args) {
        // 创建阻塞队列
        SynchronousQueue<Integer> synchronousQueue = new SynchronousQueue<>();
        // 一个线程放，一个线程取
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    System.out.println("准备放入" + i);
                    synchronousQueue.put(i);
                    System.out.println(i + "被取走了");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    Integer take = synchronousQueue.take();
                    System.out.println("取到数字" + take);
                    // 休眠一秒
                    TimeUnit.SECONDS.sleep(1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
